package com.cgycms.webdeploy.storage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName : ServersLoad
 * @Description : 服务器配置加载
 * @Author : 王力超
 * @Date: 2020-10-14 18:50
 */
@Configuration
public class ServersLoad {

    private static Logger log = LoggerFactory.getLogger(ServersLoad.class);

    private static List<Servers> servers = null;

    @Autowired
    private DeployConfig deployConfig;

    private void loadServers() {
        try {
            Resource resource = null;
            String configPath = deployConfig.getConfigPath();
            if (!StringUtils.isEmpty(configPath)) {
                log.info("指定位置加载配置文件:" + configPath);
                resource = new FileSystemResource(new File(configPath));
            } else {
                resource = new ClassPathResource("server.json");
                log.info("默认位置加载配置文件...");
            }
            String jsons = FileUtils.readFileToString(resource.getFile(), "UTF-8");
            servers = JSONUtil.toList(JSONUtil.parseArray(jsons), Servers.class);
            log.info("加载服务器信息成功~");
        } catch (IOException e) {
            log.error("加载服务器信息时出错");
            e.printStackTrace();
        }
    }

    public List<Servers> get(boolean ref) {
        if (CollectionUtil.isEmpty(servers) || ref == true) {
            loadServers();
        }
        return servers;
    }

}
